package com.wwe.kotlinstudy.util

/**
 * @name KotlinStudy
 * @package name：com.wwe.kotlinstudy.util
 * @anthor DavidZhang
 * @time 2018/4/17 14:55
 * @class describe
 */
class ListStudy {

    fun test1() {
        //声明一个只读的List，ReadOnly
        val items = listOf(1, 2, 3, 4)
        items.first() // 1
        items.last() //4
        items.filter { it % 2 == 0 } // 返回 [2, 4]
        //items.add(4) 不支持
    }

    fun test2() {
        //申明一个可变的List
        val numbers: MutableList<Int> = mutableListOf(1, 2, 3)
        numbers.add(4)
    }

    fun test3() {
        val numbers: MutableList<Int> = mutableListOf(1, 2, 3)
        val datas: List<Int> = numbers //不可变List
        numbers.add(4)
        //datas.clean() 不支持
        numbers.clear()
    }

    fun test4() {
        //创建Set
        val datas = hashSetOf(1, 2, 3)
    }

    fun test5() {
        val numbers: MutableList<Int> = mutableListOf(1, 2, 3)
        val item = numbers.firstOrNull()
    }

    fun test6(): String {
        val lists = listOf("oppo", "vivo", "apple")
        if (-1 !in 0..lists.lastIndex) {
            return "-1 is out of range"
        }

        if (lists.size !in lists.indices) {
            return "lists size is out of valid list indicies range too"
        }
        return "我也无能为力"
    }

    fun test7() {
        val datas = listOf("google", "facebook", "square")
        var index = 0
        while (index < datas.size) {
            print("item at $index is ${datas[index]}")
            index++
        }
    }

    /**注意这种“在区间上遍历”会编译成优化的实现而不会创建额外对象。*/
    fun test8() {
        val items = listOf("apple", "banana", "orange")
        for (index in items.indices) {
            println("item at $index is ${items[index]}")
        }
    }

    /**这种也是比较高效的遍历方式*/
    fun test9() {
        val array = listOf("apple", "banana", "orange")
        for ((index, value) in array.withIndex()) {
            println("the element at $index is $value")
        }
    }

    /**如果在函数被调用以前，函数的参数(通常是参数中的最后一个)个数不能够确定，可以采用不定量参数方式:用 vararg 修饰符标记参数。
     * 调用方式：val list = asList(1, 2, 3)
     * 遇到数组：val a = arrayOf(1, 2, 3)，val list = asList(-1, 0, *a, 4)
     * 我们已经有一个数组并希望将其内容传给该函数，我们使用伸展spread操作符（在数组前面加 *)
     * */
    fun <T> asList(vararg ts: T): List<T> {
        val result = ArrayList<T>()
        for (t in ts) //ts是一个 Array
            result.add(t)
        return result
    }

}